package cn.weekimwee.firstlineofcodeforkotlin.unit6

import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_sqlite.*

class SQLiteActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sqlite)
        val helper = MyDatabaseHelper(this,"BookStore.db",null,2)
        createDatabase.setOnClickListener {
            helper.writableDatabase
        }
        addData.setOnClickListener {
            helper.writableDatabase.insert(
                    "Book",
                    null,
                    ContentValues().apply {
                        put("name","the da vinci code")
                        put("author","dan brown")
                        put("pages","454")
                        put("price","16.96")
                    }
            )
            helper.writableDatabase.insert(
                    "Book",
                    null,
                    ContentValues().apply {
                        put("name","the lost symbol")
                        put("author","dan brown")
                        put("pages","510")
                        put("price","19.95")
                    }
            )
        }
        query.setOnClickListener {
            val cursor = helper.writableDatabase.query("Book",null,null,null,null,null,null)
            if(cursor.moveToFirst()){
                do{
                    Log.e("eeeee","book name is :${cursor.getString(cursor.getColumnIndex("name"))}")
                    Log.e("eeeee","author is :${cursor.getString(cursor.getColumnIndex("author"))}")
                    Log.e("eeeee","book page is :${cursor.getInt(cursor.getColumnIndex("pages"))}")
                    Log.e("eeeee","book price is :${cursor.getDouble(cursor.getColumnIndex("price"))}")
                }while (cursor.moveToNext())
            }
            cursor.close()
        }
        update.setOnClickListener {
            helper.writableDatabase.update(
                    "Book",
                    ContentValues()
                            .apply {
                                put("price",29.95)
                            },
                    "name = ?",
                    arrayOf("the lost symbol")
            )
        }
        delete.setOnClickListener {
            helper.writableDatabase.delete(
                    "Book",
                    "pages > ?",
                    arrayOf("500")
            )
        }
    }
}
